package com.resourcestore.action;

import java.io.UnsupportedEncodingException;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import com.resourcestore.utils.*;
import com.resourcestore.utils.tag.Pagination;
import com.resourcestore.action.BaseAction;
import com.resourcestore.dao.*;
import com.opensymphony.xwork2.ActionContext;
import com.resourcestore.model.*;

public class UsersAction extends BaseAction {

	private Users users;
	private Operations operations;
	private Roles roles;
	private List<Users> listUsers;
	private List<String> listChecked = new ArrayList<String>();
	private List<Roles> listAllCheck;
	private UsersDao usersDao = new UsersDao();
	private RolesDao rolesDao = new RolesDao();
	private OperationsDao operationsDao = new OperationsDao();
	private Pagination pagination = new Pagination();
	private List<Users> listLevel = new ArrayList<Users>();
	private StudentsDao studentsDao = new StudentsDao();
	private ClassStuDao classStuDao = new ClassStuDao();
	private ClassStu classStu;
	private List<ClassStu> listClass;
	private List<String> listClassSelected;

	/**
	 * 查询返回List带分页
	 * 
	 * @throws ParseException
	 * 
	 */
	// public String listUsers() {
	//
	// users = new Users();
	// pagination.setTotal(usersDao.queryUsersNum(users));
	// listUsers = usersDao.selectUsersPage(users, pagination);
	// listUsers = dealRoleCollection(listUsers, rolesDao);
	//
	// return "default";
	// }
	/**
	 * 处理RoleCollection字符串
	 * 
	 * @throws ParseException
	 * 
	 */
	public List<Users> dealRoleCollection(List<Users> list, RolesDao rolesDao) {
		String str = null;
		String[] s = null;
		Roles rolesTemp = new Roles();
		String sTemp = null;
		for (int i = 0; i < list.size(); i++) {
			try {
				list.get(i).setGmtCreatedString(
						CommonUtil.getSysTimeFormatString(list.get(i)
								.getGmtCreated()));
				list.get(i).setGmtModifiedString(
						CommonUtil.getSysTimeFormatString(list.get(i)
								.getGmtModified()));
			} catch (ParseException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

			str = list.get(i).getRoleCollection();
			if (!str.equals(null)) {
				s = CommonUtil.split(str, ",");
				sTemp = "";
				for (int j = 0; j < s.length; j++) {
					rolesTemp.setRolesId(Integer.valueOf(s[j]));
					if (CommonUtil.isNotNullOrNotEqualsEmpty(rolesDao
							.selectRolesById(rolesTemp))) {
						rolesTemp = rolesDao.selectRolesById(rolesTemp);
					} else {
						rolesTemp.setRoleName("未知角色");
					}
					sTemp = sTemp + "<div class='noMoreLine'>["
							+ rolesTemp.getRoleName() + "]</div>";
				}
				list.get(i).setStringShowRoleName(sTemp);
			}
		}
		return list;
	}

	/**
	 * 根据条件搜索，查询返回List带分页
	 * 
	 * @throws ParseException
	 * 
	 */
	// public String searchListUsers() {
	//
	// // 对内容进行urldecoder解码
	// try {
	// users.setUserName(new String(users.getUserName().getBytes(
	// "iso-8859-1"), "UTF-8"));
	// users.setRealName(new String(users.getRealName().getBytes(
	// "iso-8859-1"), "UTF-8"));
	// users.setTelNum(new String(
	// users.getTelNum().getBytes("iso-8859-1"), "UTF-8"));
	// users.setAuthor(new String(
	// users.getAuthor().getBytes("iso-8859-1"), "UTF-8"));
	// } catch (UnsupportedEncodingException e1) {
	// // TODO Auto-generated catch block
	// e1.printStackTrace();
	// }
	//
	// pagination.setTotal(usersDao.queryUsersNum(users));
	// listUsers = usersDao.selectUsersPage(users, pagination);
	//
	// listUsers = dealRoleCollection(listUsers, rolesDao);
	// return newpath("/Users/listUsers.jsp");
	// }
	/**
	 * 预处理插入信息
	 */
	public String preInsertUsers() {

		listAllCheck = rolesDao.selectRoles();

		return newpath("/Users/insertUsers.jsp");
	}

	/**
	 * 插入一条数据
	 */
	public String insertUsers() {
		users.setPassword(SHA1Util.hex_sha1(users.getPassword()));
		try {
			users.setGmtCreated(CommonUtil.getSysTimeFormatNum());
			users.setGmtModified(CommonUtil.getSysTimeFormatNum());
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		// int userId = usersDao.insertAndReturnPK(users);

		// Users usersTemp = new Users();
		// usersTemp = users;
		// usersTemp.setUsersLevelId(userId);
		// users.setUsersLevelId(userId);
		usersDao.insertUsers(users);

		return redirect(this.getUrl());
	}

	/**
	 * 更新之前加载原信息
	 * 
	 */
	public String preUpdateUsers() {
		users = usersDao.selectUsersById(users);
		// users.setUsersLevelId(users.getUserId());
		//users = usersDao.selectUsersLevelById(users);

		// 将角色字符串处理为列表
		String str = users.getRoleCollection();
		String[] s = CommonUtil.split(str, ",");
		for (int i = 0; i < s.length; i++) {
			listChecked.add(s[i]);
		}
		listAllCheck = rolesDao.selectRoles();

		return newpath("/Users/updateUsers.jsp");
	}

	/**
	 * 更新信息
	 * 
	 */
	public String updateUsers() {

		try {
			// users.setGmtCreated(CommonUtil.getSysTimeFormatNum());
			users.setGmtModified(CommonUtil.getSysTimeFormatNum());
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		//如果密码不为空则更新密码，为空则不更新保留原密码
		if (CommonUtil.isNotNullOrNotEqualsEmpty(users.getPassword())) {
			users.setPassword(SHA1Util.hex_sha1(users.getPassword()));
			usersDao.updateUsersHasPassword(users);
		}else{
			usersDao.updateUsers(users);
		}
		
		//users.setUsersLevelId(users.getUserId());
		//usersDao.updateUsersLevel(users);

		return redirect(this.getUrl());
	}

	/**
	 * 返回首页
	 */
	public String returnIndex() {
		return newpath("/Main/main.jsp");
	}
	
	/**
	 * 删除信息
	 */
	public String deleteUsers() {
		usersDao.deleteUsers(users);
		// users.setUsersLevelId(users.getUserId());
		// usersDao.deleteUsersLevel(users);
		return redirect(this.getUrl());
	}

	/**
	 * 批量删除信息
	 */
	public String deleteMoreUsers() {
		usersDao.deleteMoreUsers(users);
		// usersDao.deleteMoreUsersLevel(users);
		return redirect(this.getUrl());
	}

	/**
	 * 将某一用户的角色字符串处理成名称列表
	 * 
	 * @throws ParseException
	 * 
	 */
	public Users dealRoleCollectionUsers(Users users, RolesDao rolesDao) {
		String str = null;
		String[] s = null;
		Roles rolesTemp = new Roles();
		String sTemp = null;

		str = users.getRoleCollection();
		if (str != null) {
			s = CommonUtil.split(str, ",");
			sTemp = "";
			for (int j = 0; j < s.length; j++) {
				rolesTemp.setRolesId(Integer.valueOf(s[j]));
				if (CommonUtil.isNotNullOrNotEqualsEmpty(rolesDao
						.selectRolesById(rolesTemp))) {
					rolesTemp = rolesDao.selectRolesById(rolesTemp);
				} else {
					rolesTemp.setRoleName("未知角色");
				}
				sTemp = sTemp + " [" + rolesTemp.getRoleName() + "] ";
			}
			users.setStringShowRoleName(sTemp);
		}
		return users;
	}

	/**
	 * 列出用户所拥有的操作
	 * 
	 * @throws ParseException
	 * 
	 */
	public List<Operations> listOperByUserName(Users users) {
		String str = "";
		String[] s = null;
		Roles rolesTemp = new Roles();
		String sTemp = "";
		List<Operations> listOper = new ArrayList<Operations>();
		String operString = "";
		Operations operTemp = new Operations();

		str = users.getRoleCollection();
		if (str != null) {
			s = CommonUtil.split(str, ",");
			sTemp = "";
			for (int j = 0; j < s.length; j++) {
				rolesTemp.setRolesId(Integer.valueOf(s[j]));
				if (CommonUtil.isNotNullOrNotEqualsEmpty(rolesDao
						.selectRolesById(rolesTemp))) {
					operString = operString
							+ ","
							+ rolesDao.selectRolesById(rolesTemp)
									.getOperCollection();
				}
			}
			// 处理合并后的角色字串
			s = CommonUtil.split(operString, ",");
			s = CommonUtil.distinctArray(s);
			for (int j = 0; j < s.length; j++) {
				operTemp.setOperId(Integer.valueOf(s[j]));
				if (CommonUtil.isNotNullOrNotEqualsEmpty(operationsDao
						.selectOperationsById(operTemp))) {
					operTemp = operationsDao.selectOperationsById(operTemp);
				} else {
					operTemp.setOperName("未知模块");
				}
				listOper.add(operTemp);
			}
		}

		return listOper;
	}

	/**
	 * 用户登录验证
	 */
	public String login() {

		Users result = new Users();
		Students resultStu = new Students();
		List<Operations> listOper;
		Operations operStu = new Operations();

		// 判断验证码是否正确
//		if (users.getTxtCheck().equals(this.getSession().get("rand"))) {
			// 判断用户类型
			if (users.getUserType().equals("admin")) {
				users.setPassword(SHA1Util.hex_sha1(users.getPassword()));
				result = usersDao.loginAdmin(users);
				if (CommonUtil.isNotNullOrNotEqualsEmpty(result)) {

					// 加角色列表
					result = dealRoleCollectionUsers(result, rolesDao);

					listOper = listOperByUserName(result);

					this.getSession().put("listOperByUserName", listOper);
					this.getSession().put("roleNameString",
							result.getStringShowRoleName());
					this.getSession().put("realName", result.getRealName());
					this.getSession().put("userType", users.getUserType());
					this.getSession().put("userName", result.getUserName());
					this.getSession().put("userLevel", result.getLevel());

					return gotoPageByUserType("/Main/main.jsp", "newpath",
							"admin");
				} else {
					return redirect("/error.jsp?error=2");
				}
			} else if (users.getUserType().equals("stu")) {
				Students students = new Students();
				students.setPassword(SHA1Util.hex_sha1(users.getPassword()));
				students.setStuNum(users.getUserName());
				resultStu = studentsDao.loginStu(students);
				if (CommonUtil.isNotNullOrNotEqualsEmpty(resultStu)) {

					listOper = new ArrayList<Operations>();
					// 加角色列表
					operStu.setOperName("进入菜单");
					operStu.setOperUrl("");
					listOper.add(operStu);

					this.getSession().put("listOperByUserName", listOper);
					this.getSession().put("roleNameString", "[学生]");
					this.getSession().put("realName", resultStu.getStuName());
					this.getSession().put("userType", users.getUserType());
					this.getSession().put("userName", resultStu.getStuNum());

					return gotoPageByUserType("/Main/main.jsp", "newpath",
							"stu");
				} else {
					return redirect("/error.jsp?error=2");
				}
			}
//		} else {
//			return redirect("/error.jsp?error=8");
//		}
		return "input";
	}

	/**
	 * 用户注销
	 */
	public String logout() {
		String returnUrl = "";
		Map session = ActionContext.getContext().getSession();
		if (null == session.get("userName")) {
			returnUrl = "/default.html";
		}
		this.getSession().remove("userName");
		returnUrl = "/default.html";

		return redirect(returnUrl);
	}

	/**
	 * 插入密码表单页
	 */

	public String preUpdatePassword() {

		return newpath("/Users/updatePassword.jsp");
	}
	
	/**
	 * 用户密码修改
	 */

	public String updatePassword() {

		Map session = ActionContext.getContext().getSession();
		String userName = "";
		userName = (String) session.get("userName");
		if (!userName.equals("")) {
			users.setUserName(userName);
			users.setPassword(SHA1Util.hex_sha1(users.getPassword()));
			usersDao.updatePasswordByUserName(users);
		}

		return redirect("/Users/updatePassword_do.jsp");
	}

	/**
	 * 处理ClassCollection字符串
	 * 
	 * @throws ParseException
	 * 
	 */
	public List<Users> dealClassCollection(List<Users> list,
			ClassStuDao classStuDao) {
		String str = null;
		String[] s = null;
		ClassStu classStuTemp = new ClassStu();
		String sTemp = null;
		for (int i = 0; i < list.size(); i++) {
			try {
				list.get(i).setGmtCreatedString(
						CommonUtil.getSysTimeFormatString(list.get(i)
								.getGmtCreated()));
				list.get(i).setGmtModifiedString(
						CommonUtil.getSysTimeFormatString(list.get(i)
								.getGmtModified()));
			} catch (ParseException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			str = list.get(i).getClassCollection();
			if (str != null) {
				s = CommonUtil.split(str, ",");
				sTemp = "";
				for (int j = 0; j < s.length; j++) {
					classStuTemp.setClassId(Integer.valueOf(s[j]));
					if (CommonUtil.isNotNullOrNotEqualsEmpty(classStuDao
							.selectClassStuById(classStuTemp))) {
						classStuTemp = classStuDao
								.selectClassStuById(classStuTemp);
					} else {
						classStuTemp.setClassName("未知班级");
					}
					sTemp = sTemp + "<div class='noMoreLine'>["
							+ classStuTemp.getClassName() + "]</div>";
				}
				list.get(i).setStringShowClassName(sTemp);
			}
		}
		return list;
	}

	/**
	 * 等级用户 查询返回List带分页
	 * 
	 * @throws ParseException
	 * 
	 */
	public String listUsers() {

		users = new Users();
		//users.setLevel(-1);
		pagination.setTotal(usersDao.queryUsersNum(users));
		listUsers = usersDao.selectUsersPage(users, pagination);
		listUsers = dealRoleCollection(listUsers, rolesDao);
		listUsers = dealClassCollection(listUsers, classStuDao);

		for (int i = 0; i < listUsers.size(); i++) {
			if (listUsers.get(i).getLevel() == 1) {
				listUsers.get(i).setLevelString("院级");
			} else if (listUsers.get(i).getLevel() == 2) {
				listUsers.get(i).setLevelString("系级");
			} else if (listUsers.get(i).getLevel() == 3) {
				listUsers.get(i).setLevelString("班级");
			}
		}

		Users usersTemp1 = new Users();
		Users usersTemp2 = new Users();
		Users usersTemp3 = new Users();
		usersTemp1.setLevel(1);
		usersTemp1.setLevelString("院级");
		usersTemp2.setLevel(2);
		usersTemp2.setLevelString("系级");
		usersTemp3.setLevel(3);
		usersTemp3.setLevelString("班级");
		listLevel.add(usersTemp1);
		listLevel.add(usersTemp2);
		listLevel.add(usersTemp3);

		return "default";
	}

	/**
	 * 等级用户 根据条件搜索，查询返回List带分页
	 * 
	 * @throws ParseException
	 * 
	 */
	public String searchListUsers() {

		// 对内容进行urldecoder解码
		try {
			users.setUserName(new String(users.getUserName().getBytes(
					"iso-8859-1"), "UTF-8"));
			users.setRealName(new String(users.getRealName().getBytes(
					"iso-8859-1"), "UTF-8"));
			users.setTelNum(new String(
					users.getTelNum().getBytes("iso-8859-1"), "UTF-8"));
			users.setAuthor(new String(
					users.getAuthor().getBytes("iso-8859-1"), "UTF-8"));
			users.setDepartmentName(new String(users.getDepartmentName()
					.getBytes("iso-8859-1"), "UTF-8"));
		} catch (UnsupportedEncodingException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
//		if (!CommonUtil.isNotNullOrNotEqualsEmpty(users.getLevel())) {
//			users.setLevel(-1);
//		}

		pagination.setTotal(usersDao.queryUsersNum(users));
		listUsers = usersDao.selectUsersPage(users, pagination);

		listUsers = dealRoleCollection(listUsers, rolesDao);
		listUsers = dealClassCollection(listUsers, classStuDao);
		for (int i = 0; i < listUsers.size(); i++) {
			if (listUsers.get(i).getLevel() == 1) {
				listUsers.get(i).setLevelString("院级");
			} else if (listUsers.get(i).getLevel() == 2) {
				listUsers.get(i).setLevelString("系级");
			} else if (listUsers.get(i).getLevel() == 3) {
				listUsers.get(i).setLevelString("班级");
			}
		}

		Users usersTemp1 = new Users();
		Users usersTemp2 = new Users();
		Users usersTemp3 = new Users();
		usersTemp1.setLevel(1);
		usersTemp1.setLevelString("院级");
		usersTemp2.setLevel(2);
		usersTemp2.setLevelString("系级");
		usersTemp3.setLevel(3);
		usersTemp3.setLevelString("班级");
		listLevel.add(usersTemp1);
		listLevel.add(usersTemp2);
		listLevel.add(usersTemp3);

		return newpath("/Users/listUsers.jsp");
	}

	public Users getUsers() {
		return users;
	}

	public void setUsers(Users users) {
		this.users = users;
	}

	public List<Users> getListUsers() {
		return listUsers;
	}

	public void setListUsers(List<Users> listUsers) {
		this.listUsers = listUsers;
	}

	public Roles getRoles() {
		return roles;
	}

	public void setRoles(Roles roles) {
		this.roles = roles;
	}

	public List<String> getListChecked() {
		return listChecked;
	}

	public void setListChecked(List<String> listChecked) {
		this.listChecked = listChecked;
	}

	public List<Roles> getListAllCheck() {
		return listAllCheck;
	}

	public void setListAllCheck(List<Roles> listAllCheck) {
		this.listAllCheck = listAllCheck;
	}

	public Pagination getPagination() {
		return pagination;
	}

	public void setPagination(Pagination pagination) {
		this.pagination = pagination;
	}

	public Operations getOperations() {
		return operations;
	}

	public void setOperations(Operations operations) {
		this.operations = operations;
	}

	public List<Users> getListLevel() {
		return listLevel;
	}

	public void setListLevel(List<Users> listLevel) {
		this.listLevel = listLevel;
	}

	public ClassStu getClassStu() {
		return classStu;
	}

	public void setClassStu(ClassStu classStu) {
		this.classStu = classStu;
	}

	public List<ClassStu> getListClass() {
		return listClass;
	}

	public void setListClass(List<ClassStu> listClass) {
		this.listClass = listClass;
	}

	public List<String> getListClassSelected() {
		return listClassSelected;
	}

	public void setListClassSelected(List<String> listClassSelected) {
		this.listClassSelected = listClassSelected;
	}

}
